const fs = require("fs");
const AesSecurity = require("@/security/aes.security");
const redisClient = require("@/redis/redis-client");
const fileBusinessService = require("@/common/file-business.service");
const { Result } = require("@/libs/result");
const aesSecurity = new AesSecurity();

/**
 * 文件下载中间件
 * @param {*} ctx
 * @param {*} next
 */
const fileDownloadMiddleware = async (ctx, next) => {
	try {
		const { code, filename } = ctx.params;
		// 验证code是否有效
		const cacheKey = `file:preview:${code}`;
        if (!code || !filename) {
            ctx.status = 404;
			ctx.body = Result.Failed("File not found");
			return;
		}
		const cacheFile = await redisClient.get(cacheKey);
		// 缓存中是否存在
        if (!cacheFile) {
            ctx.status = 404;
			ctx.body = Result.Failed("File not found");
			return;
		}
		// 验证有效期
		if (cacheFile.extTime && Date.now() > cacheFile.extTime) {
			fileBusinessService.deletePreviewExpiredFile(cacheKey); // 删除过期的文件
            ctx.status = 404;
			ctx.body = Result.Failed("File not found");
			return;
		}
		// 验证名称
        if (cacheFile.name !== filename) {
            ctx.status = 404;
			ctx.body = Result.Failed("File not found");
			return;
		}
		let redisFile = aesSecurity.decrypt(cacheFile.code); // 解密内容
		redisFile = redisFile ? JSON.parse(redisFile) : {}; // 转为json
		const filePath = redisFile.path;

		// 检查文件是否存在
		if (!fs.existsSync(filePath)) {
			ctx.status = 404;
			ctx.body = Result.Failed("File not found");
			return;
		}
		// 设置响应头
		ctx.set("Content-Type", "application/octet-stream");
		ctx.set("Content-Disposition", `attachment; filename=${filename}`);
		ctx.set("Content-Length", fs.statSync(filePath).size);
		ctx.body = fs.createReadStream(filePath); // 创建可读流并管道到响应
	} catch (error) {
		console.log("文件下载异常：", error);
		ctx.body = Result.Failed(error);
	}
};

module.exports = fileDownloadMiddleware;
